package math2;

import inf.math.LinAlg;

/**
 * 
 * @author hbui
 * 
 */
public class MultFunctionRnToR extends FunctionRnToR {

	private double alpha;
	private FunctionRnToR u;
	private FunctionRnToR v;

	public MultFunctionRnToR(double alpha, FunctionRnToR u, FunctionRnToR v) {
		this.alpha = alpha;
		this.u = u;
		this.v = v;
	}

	@Override
	public double valueAt(double... x) {
		return alpha * u.valueAt(x) * v.valueAt(x);
	}

	public double[] gradientAt(double... x) {
		double[] du = u.gradientAt(x);
		double[] dv = v.gradientAt(x);
		double[] tmp = dv.clone();
		LinAlg.add(x.length, v.valueAt(x), du, u.valueAt(x), tmp);
//		LinAlg.scale(x.length, alpha, tmp, tmp);
		for (int i = 0; i < x.length; i++) {
			tmp[i] *= alpha;
		}
		return tmp;
	}

	public int getP() {
		if (this.u.getP() == -1 || this.v.getP() == -1) {
			return -1;
		} else if (this.u.getP() == 0 || this.v.getP() == 0) {
			return 0;
		} else {
			return this.u.getP() + this.v.getP();
		}
	}
}
